#include "RequestHandler.h"

RequestHandler::RequestHandler() 
    : m_dbManager(DatabaseManager::getInstance())  // 使用DatabaseManager的单例
{
}


//解析操作
RequestHandler::Operation RequestHandler::parseOperation(const string & opStr)
{
    if(opStr == "add") return ADD_ACCOUNT;
    if(opStr == "delete") return DELETE_ACCOUNT;
    if(opStr == "update") return UPDATE_ACCOUNT;
    if(opStr == "query") return QUERY_ACCOUNT;  //查询操作
    if(opStr == "login") return LOGIN_ACCOUNT; //登陆
    return UNKNOWN;
}


//处理请求
string RequestHandler::handleRequest(const string& request)
{
    Json::Value root;
    //读取器
    Json::CharReaderBuilder builder;
    //写入器
    Json::StreamWriterBuilder writerbuilder;
    unique_ptr<Json::CharReader> reader(builder.newCharReader());
    
    //错误的信息提示 
    string errors;
    //第一个参数为开始的地址，第二个为结束的地址，第三个为解析的结果，第四个为解析的错误信息
    if(!reader->parse(request.c_str(),request.c_str() + request.size(),&root,&errors))
    {
        Json::Value response;
        response["status"] = "error";
        response["messgae"] = "Invalid JSON format";  //格式错误
        return Json::writeString(writerbuilder,response);  //返回错误的信息,使用写入器来返回
    }
    if(!root.isMember("functionID") || !root.isMember("data"))
    {
        Json::Value response;
        response["status"] = "error";
        response["errCODE"] = "Missing functionID or data field";
        return Json::writeString(writerbuilder,response);
    }

    Operation op = parseOperation(root["functionID"].asString());
    Json::Value result;
    switch (op)
    {
    case ADD_ACCOUNT:
        result = addAccount(root["data"]);
        break;
    case DELETE_ACCOUNT:
        result = deleteAccount(root["data"]);
        break;
    case UPDATE_ACCOUNT:
        result = updateAccount(root["data"]);
        break;
    case QUERY_ACCOUNT:
        result = queryAccount(root["data"]);
        break;
    case LOGIN_ACCOUNT:
        result = loginAccount(root["data"]);
    default:
        result["status"] = "error";
        result["errCODE"] = "unknow functionID";
        break;
    }
    return Json::writeString(writerbuilder,result);
}




//解析data数据将data数据中的username和password解析出来
Json::Value RequestHandler::addAccount(const Json::Value& data)
{
 
    Json::Value response;
        if(!data.isMember("userID") || !data.isMember("password") || !data.isMember("phonenum") || !data.isMember("username"))
    {
        response["status"] = "error";
        response["errCode"] = "Missing userID or password or username or phonenum";
        return response;  //这里只用去返回response因为上方回通过writebuilder来写回
    }
    string userID = data["userID"].asString();
    string username = data["username"].asString();
    string password = data["password"].asString();
    string phonenum = data["phonenum"].asString();
    string sql = "INSERT INTO accounts(userID,username,password,phonenum) VALUES(?,?,?,?)";
    sqlite3_stmt* stmt = m_dbManager.prepare(sql);//将解析好的数据数据传入stmt
    if(!stmt)
    {
        response["status"] = "error";
        response["errCODE"] = "Database prepare failed";
        return response;
    }

    sqlite3_bind_text(stmt,1,userID.c_str(),-1,SQLITE_STATIC);
    sqlite3_bind_text(stmt,2,username.c_str(),-1,SQLITE_STATIC);
    sqlite3_bind_text(stmt,3,password.c_str(),-1,SQLITE_STATIC);
    sqlite3_bind_text(stmt,4,phonenum.c_str(),-1,SQLITE_STATIC);
    if(sqlite3_step(stmt) == SQLITE_DONE)
    {
        response["status"] = "success";
        response["errCODE"] = "Account created";
    }
    else
    {
        response["status"] = "error";
        response["errCODE"] = sqlite3_errmsg(m_dbManager.getDB());
    }

    sqlite3_finalize(stmt);
    return response;
}

//删除操作的解析
Json::Value RequestHandler::deleteAccount(const Json::Value& data)
{
     
       Json::Value response;  //结果的返回
              if(!data.isMember("userID") || !data.isMember("password"))
    {
        response["status"] = "error";
        response["errCODE"] = "Missing username or password";
        return response;  //这里只用去返回response因为上方回通过writebuilder来写回
    }
    string userID = data["userID"].asString();
    string password = data["password"].asString();
 string sql = "DELETE FROM  accounts WHERE userID=? AND password = ?";
    sqlite3_stmt* stmt = m_dbManager.prepare(sql);//将解析好的数据数据传入stmt
    if(!stmt)
    {
        response["status"] = "error";
        response["errCODE"] = "Database prepare failed";
        return response;
    }
    sqlite3_bind_text(stmt,1,userID.c_str(),-1,SQLITE_STATIC);
    sqlite3_bind_text(stmt,2,password.c_str(),-1,SQLITE_STATIC);
    if(sqlite3_step(stmt) == SQLITE_DONE)
    {
        response["status"] = "success";
        response["errCODE"] = "Account delete";
    }
    else
    {
        response["status"] = "error";
        response["errCODE"] = sqlite3_errmsg(m_dbManager.getDB());
    }

    sqlite3_finalize(stmt);
    return response;

}


//更新也需要解析判断有无这个username和password
Json::Value RequestHandler::updateAccount(const Json::Value& data)
{
   
    Json::Value response;  //结果的返回
              if(!data.isMember("userID") || !data.isMember("password"))
    {
        response["status"] = "error";
        response["errCODE"] = "Missing username or password";
        return response;  //这里只用去返回response因为上方回通过writebuilder来写回
    }
    string username = data["username"].asString();
    string password = data["password"].asString();
    string phonenum = data["phonenum"].asString();
    string sql = "UPDATE accounts SET password = ? WHERE username = ? AND phonenum = ?";
    sqlite3_stmt* stmt = m_dbManager.prepare(sql);//将解析好的数据数据传入stmt
    if(!stmt)
    {
        response["status"] = "error";
        response["errCODE"] = "Database prepare failed";
        return response;
    }
    sqlite3_bind_text(stmt,1,password.c_str(),-1,SQLITE_STATIC);
    sqlite3_bind_text(stmt,2,username.c_str(),-1,SQLITE_STATIC);
    sqlite3_bind_text(stmt,3,phonenum.c_str(),-1,SQLITE_STATIC);
    if(sqlite3_step(stmt) == SQLITE_DONE)
    {
        response["status"] = "success";
        response["errCODE"] = "Account update";
    }
    else
    {
        response["status"] = "error";
        response["errCODE"] = sqlite3_errmsg(m_dbManager.getDB());
    }

    sqlite3_finalize(stmt);
    return response;

}

//请求操作同样是需要解析数据中的username和password
Json::Value RequestHandler::queryAccount(const Json::Value& data)
{ 
  
    Json::Value response;  //结果的返回
              if(!data.isMember("userID"))
    {
        response["status"] = "error";
        response["errCODE"] = "Missing userID";
        return response;  //这里只用去返回response因为上方回通过writebuilder来写回
    }
    string userID = data["userID"].asString();
    
    string sql = "SELECT * FROM  accounts WHERE userID=?";
    sqlite3_stmt* stmt = m_dbManager.prepare(sql);//将解析好的数据数据传入stmt
    if(!stmt)
    {
        response["status"] = "error";
        response["errCODE"] = "Database prepare failed";
        return response;
    }
    sqlite3_bind_text(stmt,1,userID.c_str(),-1,SQLITE_STATIC);
    
    if(sqlite3_step(stmt) == SQLITE_ROW)
    {
        response["status"] = "success";
        response["errCODE"] = "Account query";

        //  // 获取列数
        // int colCount = sqlite3_column_count(stmt);

        // for(int i = 0; i < colCount; i++) 
        // {
        //      switch(sqlite3_column_type(stmt, i)) 
        //      {
        //         case SQLITE_INTEGER:
        //             response["phonenum"] = sqlite3_column_int(stmt, i);
        //             break;
        //         case SQLITE_TEXT:
        //             response["password"] = reinterpret_cast<const char*>(sqlite3_column_text(stmt, i));
        //             response["username"] = reinterpret_cast<const char*>(sqlite3_column_text(stmt, i));
        //             break;
        //      }
        // }
    }
    else
    {
        response["status"] = "error";
        response["errCODE"] = "dont have this userID";
    }


    sqlite3_finalize(stmt);  //释放stmt
    return response;

}


Json::Value RequestHandler::loginAccount(const Json::Value& data)
{
   
    Json::Value response;  //结果的返回
              if(!data.isMember("userID") || !data.isMember("password"))
    {
        response["status"] = "error";
        response["errCODE"] = "Missing username or password";
        return response;  //这里只用去返回response因为上方回通过writebuilder来写回
    }
    else 
    {
        response["status"] = "success";
        response["errCODE"] = "login in";
    }
    return response;

}